package com.smileymedia.smil;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.TextView;

import com.smileymedia.R;
import com.smileymedia.core.Constants;
import com.smileymedia.net.HttpFileUploader;
import com.smileymedia.smil.content.SmilContent;
import com.smileymedia.smil.stage.Stage;
import com.smileymedia.smil.stage.Timeline;
import com.smileymedia.util.SDCardUtil;
import com.smileymedia.util.ToastUtil;
import com.smileymedia.view.HelloView;
import com.smileymedia.view.SmilRendererLayout;
import com.smileymedia.view.TransparentView;

/**
 * Render Smil Message
 * @author greg
 *
 */
public class SmilRendererActivity extends Activity {    
	protected static final int MSG_HIDE_CONTROLS = 1;

	protected static final int MSG_FILE_DOWNLOAD_STARTED= 2;

	protected static final  int MSG_FILE_DOWNLOAD_CIOMPLETED = 3;

	private final String TAG = SmilRendererActivity.class.getSimpleName();

	private boolean isControlPanelVisible=false;
	private SmilContentHandler mySmilHandler;

	private TransparentView mRenderView; 
	private ToastUtil mToast;

	/* Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Bundle extras = getIntent().getExtras();
		String fileName=extras.getString("smil");
	 
		
		//Setup full screenrequest
		/*
		 requestWindowFeature(Window.FEATURE_NO_TITLE);  
	        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
	                                WindowManager.LayoutParams.FLAG_FULLSCREEN);  
		 */

		mToast=new ToastUtil(getBaseContext());
		Stage stage = null;
		try {
			/* Get a SAXParser from the SAXPArserFactory. */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();

			/* Get the XMLReader of the SAXParser we created. */
			XMLReader xr = sp.getXMLReader();
			mySmilHandler = new SmilContentHandler();
			xr.setContentHandler(mySmilHandler);
			/* Parse the xml-data from our URL. */

			xr.parse(new InputSource(new ByteArrayInputStream(SDCardUtil.readBytes(getBaseContext(), fileName, true))));
			stage=mySmilHandler.getStage();
			
			//downloadResources(stage);
			
			stage.print();
			/* Parsing has finished. */			
		} catch (Exception e) {
			/* Display any Error to the GUI. */
			Log.e(TAG, "HomeActivityError", e);
		}

		SmilRendererLayout smilRendererLayout = new SmilRendererLayout(this);
		smilRendererLayout.setStage(stage);
		
		
		HelloView helloView = new HelloView(this);
		helloView.mStage=stage;
		setContentView(helloView);
		
		stage.play();
		
		if(true)return;
		
		//setContentView(R.layout.main);

		mRenderView = (TransparentView) findViewById(R.id.renderview);
		mRenderView.setVisibility(View.INVISIBLE);
		Log.d(TAG, "****** RV= " + mRenderView);

		
		Button btnSendSms=(Button) findViewById(R.id.button_send_sms);
		btnSendSms.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				Log.d(TAG, "Button Clicked");

				//uploadFile();

				byte[] fileBuffer=SDCardUtil.readBytes(getBaseContext(), "/sdcard/banner.gif", true);

				//HttpFileUploader htfu = new HttpFileUploader("http://smileymediastore.appspot.com/upload","", "banner.gif");
				String sUrl="http://192.168.1.4:8888/upload";
				sUrl = com.smileymedia.util.URLUtil.executeGet("http://192.168.102.104:8888/list");
				Log.i(TAG, " Callback Url= "+sUrl);

				//uploadFile();

				HttpFileUploader htfu = new HttpFileUploader("http://192.168.102.104:8888"+sUrl, "", "banner.gif");
				htfu.doStart(fileBuffer);


				/*
				  WORKS Attaches picture to the MMS
			    Intent sendIntent = new Intent(Intent.ACTION_SEND);
		        sendIntent.putExtra("sms_body", "Content of the SMS goes here..."); 
		        sendIntent.putExtra("address", "15804023145");
		        sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://media/external/images/media/1"));
		        sendIntent.setType("image/png");  
		        startActivity(sendIntent);
				 */
				/*
				//sendIntent.setType("vnd.android-dir/mms-sms");
				String msg= "Check out this SMIL presentation <a href='http://www.google.com/layout.smil> Smil Layout</a>";
				Intent sendIntent = new Intent(Intent.ACTION_SEND);
				sendIntent.putExtra("sms_body", msg); 
				sendIntent.putExtra("address", "15804023145");
				sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://media/external/images/media/1"));
				sendIntent.setType("image/png");  


				// sendIntent.setType("vnd.android-dir/mms-sms");

				// startActivity(sendIntent);

				//startActivity(Intent.createChooser(sendIntent, "Send SMIL"));


				//sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://media/external/images/media/1"));
				//startActivity(sendIntent);

				SmsManager sms=SmsManager.getDefault();
				sms.sendTextMessage("1-580-402-3145", null, msg, null, null);
				mToast.showShort("SMS Sent");
				 */
			}
		});
	}

	private ProgressDialog pd;
	private void downloadResources(final Stage stage) {
		pd = ProgressDialog.show(this, "Downloading Resources", "Downloading Resources", true,  false);

		Thread downloder=new Thread(new Runnable(){
			public void run() {
				DateFormat df = new SimpleDateFormat("MM-dd-yyyy hh mm ss");
				String folder=df.format(new Date());
				folder="tmp";
				SDCardUtil.mkdir (getBaseContext(), folder);
				for(Timeline timeline:stage.getAllTimelines()){
					SmilContent content = timeline.getContent();
					if(content.isDowloadable == false)continue;
					
					String src=content.getSource();
					
					Message msg = Message.obtain(downlodHandler, MSG_FILE_DOWNLOAD_STARTED);
					msg.obj=src;
					
					downlodHandler.sendMessage(msg);					
					byte[] data=com.smileymedia.util.URLUtil.readURLtoByte(src);
					
					String[] fnames = src.split("/");
					String fileName=fnames[fnames.length-1];
					
					String sdFileName=folder+"/"+fileName;

					Log.w(TAG, "Downloded : "+ fileName+":"+data.length);
					
					//Assemble filename
				   
					Log.w(TAG, "sdFileName : "+ sdFileName);
					SDCardUtil.writeFile(getBaseContext(), sdFileName, data);
				}
				
				downlodHandler.sendMessage(Message.obtain(downlodHandler, MSG_FILE_DOWNLOAD_CIOMPLETED));
			}        	
		});
		
		downloder.start();
	}

	private Handler downlodHandler=new Handler(){
		public void handleMessage(Message msg) {  
			switch(msg.what){
			case MSG_FILE_DOWNLOAD_STARTED:{
				String fileName=(String) msg.obj;
				pd.setMessage(String.format("Downloading : %s", fileName));
				break;
			}
			
			case MSG_FILE_DOWNLOAD_CIOMPLETED:{
				pd.dismiss();
				break;
			}
			
			}
		}
	};
	
	

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if(true)return true;
		
		//we can have only one control panel
		if(isControlPanelVisible){
			return super.onTouchEvent(event);
		}
		Log.d(TAG, "TOUCHED = "+event);
		mRenderView.setVisibility(View.VISIBLE);
		Timer mControlTimer=new Timer("ControlTimer");
		mControlTimer.schedule(new TimerTask() {			
			@Override
			public void run() {
				messageHandler.sendMessage(Message.obtain(messageHandler, MSG_HIDE_CONTROLS)); 
			}
		}, 3000);
		isControlPanelVisible=true;

		/*
		int color = mRenderView.mBackgroundColor;
		byte[] unpacked=BitUtil.unpack(color);

		Log.d(TAG, "color = "+color);
		for(int i=0;i<200;i++){						
			int newColor = BitUtil.pack(i, unpacked[1], unpacked[2], unpacked[3]);
		}
		 */
		return super.onTouchEvent(event);
	}


	URL u;
	public void uploadFile()
	{
		//String s=URLEncoder.encode("A Test string to send to a servlet");
		Log.d(TAG, " ----------- WRITING FILE");

		String sUrl="http://192.168.102.104:8888/upload";
		sUrl = com.smileymedia.util.URLUtil.executeGet("http://192.168.102.104:8888/list");

		try
		{
			//u = new URL("http://localhost:8888/upload");
			//"http://smileymediastore.appspot.com/upload"
			u = new URL("http://192.168.102.104:8888"+sUrl);

			// Open the connection and prepare to POST
			URLConnection uc = u.openConnection();
			uc.setDoOutput(true);
			uc.setDoInput(true);
			uc.setAllowUserInteraction(false);
			DataOutputStream dstream = new DataOutputStream(uc.getOutputStream());

			byte[] fileDate=SDCardUtil.readBytes(getBaseContext(), "/sdcard/banner.gif", true);
			// The POST line
			dstream.write(fileDate);
			dstream.close();


			// Read Response
			InputStream in = uc.getInputStream();
			BufferedReader r = new BufferedReader(new InputStreamReader(in));
			StringBuffer buf = new StringBuffer();
			String line;
			while ((line = r.readLine())!=null) {
				buf.append(line);
			}

			in.close();
			Log.d(TAG, "buf = " + buf);

		}
		catch (IOException e)
		{ 
			e.printStackTrace();	// should do real exception handling
		}	

	}


	//Instantiating the Handler associated with the main thread.
	private Handler messageHandler = new Handler() {
		public void handleMessage(Message msg) {  
			switch(msg.what){
			case MSG_HIDE_CONTROLS : {
				mRenderView.setVisibility(View.INVISIBLE);	
				isControlPanelVisible=false;
			}
			}
		}
	};
}